<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ModelController.php 315 2011-09-20 12:51:17Z beimuaihui@gmail.com $
 */

class System_ModeldetailController extends Baogg_Controller_Action {
	
	function init() {
		Zend_Loader::loadClass ( 'Model' );
		$this->model = new Model ();
		BAOGG_LANGUAGE::loadFile ( 'model' );
		
		$model_id = ( int ) $this->getRequest ()->getParam ( "model_id" );
		if ($model_id) {
			$rs_model = $this->model->getOne ( $model_id );
			$table_name = $rs_model [0] ['table_name'];
			$db_key = $rs_model [0] ['db_key'];
			$file_name = 'baogg_' . ($db_key ? $db_key . '_' : '') . str_replace ( $table_name, '_', '' );
			BAOGG_LANGUAGE::loadFile ( $file_name );
		}
	}
	
	function listAction() {
		
		global $LANG;
		$params = $this->getRequest ()->getParams ();
		$form_url = $params;
		Zend_Loader::loadClass ( "Baogg_View_Extgrid" );
		
		$model_id = ( int ) $this->getRequest ()->getParam ( "model_id" );
		
		$rs_model = $this->model->getOne ( $model_id );
		$form_height = $rs_model [0] ['form_height'] ? $rs_model [0] ['form_height'] : 300;
		$arr_model_detail = $this->model->getModelAndField ( $model_id );
		$instance = new $arr_model_detail ['class_name'] ();
		$key_field = $arr_model_detail ['key_col'];
		$lable_field = $arr_model_detail ['label_col'];
		$parent_field = isset ( $arr_model_detail ['parent_col'] ) ? $arr_model_detail ['parent_col'] : '';
		
		if (! $model_id || ! $rs_model) {
			echo "parameter model_id don't exist";
			exit ();
		}
		
		$ModelField = new ModelField ();
		$rs_model_field = $ModelField->getList ( array ("model_id" => $model_id, "model_pid" => $model_id, 'state' => 1 ), array ('sort'=>'ordering' ,'dir'=> 'asc' ) );
		
		//echo '<pre>';print_r($rs_model_field);exit;
		
		$cm = array ();
		$form_items = array ('model_id' => array ('xtype' => 'hidden', 'value' => $model_id ) );
		$Dict = new Dict ();
		//echo __FILE__.__LINE__.'<pre>';print_r($rs_model_field);exit;
		$form_url ['action'] = 'combo';
		$str_combo_url = Baogg_Controller_Url::generate ( $form_url );
		foreach ( ( array ) $rs_model_field as $v ) {
			if ($v ['is_basic']) {
				$cm [$v ['field_name']] = array ("sortable" => true, 'header' => $v ['show_name'] );
				if($v['field_name']==$key_field){
					$cm [$v ['field_name']]["cmType"]=Baogg_View_Extgrid::CMTYPE_PK;
				}
				if ($v ['dict_id'] && in_array ( $v ['field_view'], array ('combo', 'radiogroup', 'checkgroup' ) )) {
					$cm [$v ['field_name']] ['xtype'] = 'templatecolumn';
					$cm [$v ['field_name']] ['tpl'] = '{' . $v ['field_name'] . '2}';
					$cm [$v ['field_name'] . '2'] = array ('hidden' => true );
				}
			}
			
			if ($v ['field_view']) {
				
				$form_items [$v ['field_name']] = array ('xtype' => $v ['field_view'], 'fieldLabel' => $v ['show_name'] );
				if ($v ['dict_id'] && in_array ( $v ['field_view'], array ('radiogroup', 'checkboxgroup' ) )) {
					$form_items [$v ['field_name']] ['source'] = $Dict->getDictCombo ( $v ['dict_id'] );
				} else if ($v ['dict_id'] && in_array ( $v ['field_view'], array ('combo', 'itemselector' ) )) {
					$form_items [$v ['field_name']] ['store'] = $Dict->getDictCombo ( $v ['dict_id'] );
				
				} else if ($v ['field_view'] == 'textfield') {
					$form_items [$v ['field_name']] = array ('xtype' => 'combo', //'store'=>$instance->getColCombo(array(),array(),array(),array($v['field_name'])),
					'hideTrigger' => true, 'mode' => 'remote', 'queryMode' => 'remote', 'minChars' => 1, 'valueField' => $v ['field_name'], 'displayField' => $v ['field_name'], "fieldLabel" => ($v ['show_name'] ? $v ['show_name'] : null), 'forceSelection' => false, 'allowBlank' => true, 'store' => new Zend_Json_Expr ( 'new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "' . $v ['field_name'] . '",remoteSort: true,fields: ["' . $v ['field_name'] . '"],autoLoad:true,proxy: new Ext.data.HttpProxy({type:"ajax",actionMethods: { create : "POST", read : "POST", update : "POST", destroy: "POST" }, reader: {	 type: "json", 	 totalProperty: "count", root: "data"},url: "' . $str_combo_url . 'model_field_id/' . $v ['field_id'] . '/"})})' ), 'pageSize' => Baogg_View_Extgrid::$PAGE_SIZE ); //,"'.$item['displayField'].'"
				}
			}
		
		}
		
		$form_url ['action'] = "data";
		$grid = new Baogg_View_Extgrid ( $form_url, $cm );
		$grid->setSelectionModel ( true );
		$grid->setRowNumberer ( true );
		$grid->addExistButtons ( array ('add', 'remove', 'query' ), array ('edit', 'delete' ) ); //
		

		$form_url ['action'] = 'add';
		$form = new Baogg_View_Extform ( array ("url" => $form_url, "height" => $form_height, "width" => 600 ) );
		$form->addItems ( $form_items );
		$form->addExistButtons ( array ('-', 'save_grid', 'save_new', 'save', '-', 'search', '-', 'cancel' ) );
		
		
		$this->view->form = $form;
		
		$this->view->LANG = Zend_Json::encode ( $LANG );
		$this->view->grid = $grid->render ();
	
	}
	
	function dataAction() {
		$params = $this->getRequest ()->getParams ();
		
		$model_id = ( int ) $params ["model_id"];
		$Model = new Model ();
		$arr_model_detail = $Model->getModelAndField ( $model_id );
		$instance = new $arr_model_detail ['class_name'] ();
		
		$where = array ();
		$order = array ();
		$limit = array ();
		foreach ( ( array ) $params as $k => $v ) {
			if ($k == "start" || $k == "limit") {
				$limit [$k] = $v;
			} else if ($k == "sort" || $k == "dir") {
				$order [$k] = $v;
			} else {
				if ($k == $instance->myPrimary) {
					if ($v && is_numeric ( $v )) {
						$v = ( int ) $v;
						$where [$k] = $v;
					}
				} else {
					$v = '%' . $v . '%';
					$where [$k] = $v;
				}
			
			}
		}
		//echo __FILE__.__LINE__.'<br /><pre>';print_r($where);exit;
		if(!$order && in_array('ordering',$arr_model_detail['cols'])){
			$order=array('ordering'=>'asc');
		}
		$rs = $instance->getList ( $where, $order, $limit );
		$ModelField = new ModelField ();
		$rs_model_field = $ModelField->getList ( array ("model_id" => $model_id, "model_pid" => $model_id ,'dict_id>0',"field_view in ('combo','radiogroup','checkgroup','itemselector')" ), array ('ordering' => 'asc' ) );
		$arr_model_field = array ();
		foreach ( ( array ) $rs_model_field as $v ) {
			$arr_model_field [$v ['field_name']] = $v['dict_id'];
		}
		
		$Dict = new Dict ();
		$arr_dict = array ();
		foreach ( ( array ) $rs as $k => $v ) {
			foreach($arr_model_field as $col=>$dict_id){
				if(isset($v[$col])){
					if (! isset ( $arr_dict [$dict_id] )) {
						$rs_dict = $Dict->getDictCombo ( $dict_id );
						$arr_dict [$dict_id] = array ();
						foreach ( $rs_dict as $v_dict ) {
							$arr_dict [$dict_id] [$v_dict [0]] = $v_dict [1];
						}
					}
					if (isset ( $arr_dict [$dict_id] [$v[$col]] )) {
						$rs [$k] [$col . "2"] = $arr_dict [$dict_id] [$v[$col]];
					}
				}
			}
			
			/* foreach ( ( array ) $v as $col => $val ) {
				if (isset ( $arr_model_field [$col] ) && $arr_model_field [$col] ['dict_id'] && $arr_model_field [$col] ['dict_id'] && in_array ( $arr_model_field [$col] ['field_view'], array ('combo', 'radiogroup', 'checkgroup','itemselector' ) )) {
					if (! isset ( $arr_dict [$arr_model_field [$col] ['dict_id']] )) {
						$rs_dict = $Dict->getDictCombo ( $arr_model_field [$col] ['dict_id'] );
						$arr_dict [$arr_model_field [$col] ['dict_id']] = array ();
						foreach ( $rs_dict as $v ) {
							$arr_dict [$arr_model_field [$col] ['dict_id']] [$v [0]] = $v [1];
						}
					}
					if (isset ( $arr_dict [$arr_model_field [$col] ['dict_id']] [$val] )) {
						$rs [$k] [$col . '2'] = $arr_dict [$arr_model_field [$col] ['dict_id']] [$val];
					}
				
				}
			} */
		}
		
		$rs_cnt = $instance->getList ( $where, null, NULL, "count(*) as cnt" );
		
		echo Zend_Json::encode ( array ("count" => $rs_cnt [0] ['cnt'], "data" => $rs ) );
		$this->_helper->viewRenderer->setNoRender ();
	
	}
	
	function addAction() {
		$this->saveAction ();
	}
	
	function editAction() {
		$this->saveAction ();
	}
	
	function deleteAction() {
		
		$ret = array ("success" => false, "msg" => "delete_fail" );
		$id = Baogg_Controller_Action::_getParam ( 'ids' );
		
		$Model = new Model ();
		$model_id = $this->getRequest ()->getParam ( 'model_id' );
		$arr_model_detail = $Model->getModelAndField ( $model_id );
		$instance = new $arr_model_detail ['class_name'] ();
		
		if ($instance->_delete ( $id )) {
			$ret ['success'] = true;
			$ret ["msg"] = "delete_ok";
		}
		
		echo Baogg_Language::outputResult ( $ret );
		$this->_helper->viewRenderer->setNoRender ();
	}
	
	function removeAction() {
		$this->deleteAction ();
	}
	
	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		

		$ret = array ("success" => false, "msg" => "save_fail" );
		
		//check form
		if (! $this->_request->isPost ()) {
			echo Baogg_Language::outputResult ( $ret );
			exit ();
		}
		
		$formData = $this->_request->getPost ();
		
		if (! $formData) {
			echo Baogg_Language::outputResult ( $ret );
			exit ();
		}
		
		$Model = new Model ();
		$model_id = $formData ['model_id'];
		$arr_model_detail = $Model->getModelAndField ( $model_id );
		$instance = new $arr_model_detail ['class_name'] ();
		
		$arr = $instance->filterForm ( $formData );
		$action = $this->getRequest ()->getParam ( 'action' );
		$rs = $instance->getSame2 ( $arr, ' and ' );
		if ($action == 'edit') {
			if (count ( $rs ) == 0 || count ( $rs ) == 1 && $rs [0] == $arr [$instance->myPrimary]) {
				$instance->_update ( $arr, $arr [$instance->myPrimary] );
				$ret ['success'] = true;
				$ret ['msg'] = "save_ok";
			} else {
				$ret ['msg'] = "exist_same_record";
			}
		
		} else {
			//insert record
			//$permission_type = 1;
			if ($rs) {
				$ret ['msg'] = "exist_same_record";
			} else {
				unset ( $arr [$instance->myPrimary] );
				$ret ['success'] = $instance->_insert ( $arr ) > 0 ? true : false;
				$ret ['msg'] = "add_ok";
			}
		}
		
		echo Baogg_Language::outputResult ( $ret );
		
		$this->_helper->viewRenderer->setNoRender ();
	
	}

}
